import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
    state: () => ({
        token: null,
        userrole: null,
        userinfo: null
    }),
    actions: {
        setToken(token) {
            console.log('设置 Token:', token);
            this.token = token;
            localStorage.setItem('token', token);
        },
        removeToken() {
            this.token = null;
            this.userinfo = null;
            this.userrole = null;
            localStorage.removeItem('token');
            localStorage.removeItem('userinfo');
            localStorage.removeItem('userrole');
        },
        setUserrole(userrole) {
            this.userrole = userrole;
            localStorage.setItem('userrole', userrole);
        },
        setUserinfo(userinfo) {
            this.userinfo = userinfo;
            localStorage.setItem('userinfo', JSON.stringify(userinfo));
        }
    },
    getters: {
        getNickname: (state) => state.userinfo?.nickname,
        getUserId: (state) => state.userinfo?.id,
        getToken: (store) => {
            if (!store.token) {
                store.token = localStorage.getItem('token');
            }
            return store.token;
        },
        getUserrole: (store) => {
            if (!store.userrole) {
                store.userrole = localStorage.getItem('userrole');
            }
            return store.userrole;
        },
        getUserinfo: (store) => {
            if (!store.userinfo) {
                const userinfo = localStorage.getItem('userinfo');
                if (userinfo) {
                    store.userinfo = JSON.parse(userinfo);
                }
            }
            return store.userinfo;
        }
    }
});